var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
//获取应用实例
var app = getApp();
Page(Object.assign({}, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    uploadImgList: [],
    submitInfo: {},
    goodsId: "",
    action: '',
    name: "",
    price: "",
    remark: "",
    OriPrice: "",
    prop: null
  },
  getGood: function (goodsId) {
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/goods/findGoods',
      data: {
        cusmallToken: cusmallToken,
        goodsId: goodsId
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && data.ret == 0) {
          ctx.setData({
            name: data.model.goods.name,
            price: data.model.goods.customButtonText,
            OriPrice:JSON.parse(data.model.goods.prop).customoRiginalPrice
          })
          if (data.model.goods.remark) {
            ctx.setData({
              remark: data.model.goods.remark,
            })
          } else {
            ctx.setData({
              remark: ''
            })
          }
          if (data.model.goods.pics) {
            ctx.setData({
              uploadImgList: data.model.goods.pics.split(',')
            })
          }
        } else {}
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
    });
    if (options) {
      that.setData({
        goodsId: options.goodsId,
        action: options.action
      })
      options.goodsId && that.getGood(options.goodsId);
    }
  },
  bindTextInput(e) {
    var ctx = this;
    ctx.data.submitInfo[e.currentTarget.id] = e.detail.value;
  },
  handleAddImage: function () {
    let that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        wx.navigateTo({
          url: `/pages/cropper/cropper?src=${tempFilePaths[0]}&scaleXY=1.25&saveKey=uploadImgList&relative=y&isArr=y`,
          success: function (res) {},
          fail: function (res) {},
          complete: function (res) {},
        })
        // that.upload(that, tempFilePaths);
      }
    })
  },

  upload: function (page, path) {
    let vm = this;
    wx.showToast({
        icon: "loading",
        title: "正在上传"
      }),
      wx.uploadFile({
        url: cf.config.pageDomain + '/mobile/common/imgupload?cusmallToken=' + cusmallToken,
        filePath: path[0],
        name: 'file',
        header: {
          "Content-Type": "multipart/form-data"
        },
        formData: {
          //和服务器约定的token, 一般也可以放在header中
          cusmallToken: cusmallToken,
        },
        success: function (res) {
          if (res.statusCode != 200) {
            wx.showModal({
              title: '提示',
              content: '上传失败',
              showCancel: false
            })
            return;
          }
          let data = JSON.parse(res.data);
          let uploadImgList = vm.data.uploadImgList;
          uploadImgList.push(data.fileName);
          vm.setData({
            uploadImgList: uploadImgList
          });
        },
        fail: function (e) {
          console.log(e);
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
        },
        complete: function () {
          wx.hideToast(); //隐藏Toast
        }
      })
  },

  handleDelImg: function (e) {
    let vm = this;
    let idx = e.target.dataset.index;
    let imgList = vm.data.uploadImgList;
    imgList.splice(idx, 1);
    vm.setData({
      uploadImgList: imgList
    })
  },

  handleSubmit() {
    let ctx = this;
    let name = ctx.data.submitInfo.name || ctx.data.name;
    let price = ctx.data.submitInfo.price || ctx.data.price;
    let spec = ctx.data.submitInfo.spec || ctx.data.spec;
    let OriPrice = ctx.data.submitInfo.OriPrice || ctx.data.OriPrice;
    if (!name) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '请填写名称'
      })
      return;
    }
    if (!price) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '请填写价格'
      })
      return;
    }
    if (/^[0-9]+\.?[0-9]*$/.test(price)) {
      if (999999 < price) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '全数字产品价格不能超过999999！'
        })
        return;
      }
    } else {
      if (6 < price.length) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '非全数字产品价格长度不能超过6！'
        })
        return;
      }
    }
    //商品原价
    if (!OriPrice) {
      OriPrice:""
    }
    if (/^[0-9]+\.?[0-9]*$/.test(OriPrice)) {
      if (999999 < OriPrice) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '全数字产品原价不能超过999999！'
        })
        return;
      }
    } else {
      if (6 < OriPrice.length) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '非全数字产品价格长度不能超过6！'
        })
        return;
      }
    }
    if (!spec) {
      spec = '';
    }
    let imgList = "";
    if (ctx.data.uploadImgList.length) {
      imgList = ctx.data.uploadImgList.join(",")
    }
    if (!imgList) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '请上传商品图片'
      })
      return;
    }
    if (/^[0-9]+\.?[0-9]*$/.test(price)) {
      price = parseFloat(price) * 100;
    }
    if (/^[0-9]+\.?[0-9]*$/.test(OriPrice)) {
      OriPrice = parseFloat(OriPrice) * 100;
    }

    ctx.setData({
      prop: {
        customoRiginalPrice: OriPrice
      }
    })
    console.log(typeof ctx.data.prop)
    if (ctx.data.goodsId || ctx.data.action == 'edit') {
      wx.request({
        url: cf.config.pageDomain + '/applet/mobile/visitcard/goods/updateGoods',
        data: {
          cusmallToken: cusmallToken,
          name: name,
          pics: imgList,
          customButtonText: price,
          remark: spec,
          totalCount: 10,
          id: ctx.data.goodsId,
          prop: ctx.data.prop
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          var data = res.data;
          if (data && 0 === data.ret) {
            wx.showToast({
              title: "修改成功",
              icon: 'success',
              success() {
                wx.navigateBack({
                  delta: 1
                })
              },
              duration: 1000
            });
          } else {
            wx.showToast({
              title: data.msg,
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail() {},
        complete() {
          wx.hideLoading()
        }
      })
    } else {
      wx.request({
        url: cf.config.pageDomain + '/applet/mobile/visitcard/goods/addGoodsByEmployee',
        data: {
          cusmallToken: cusmallToken,
          name: name,
          pics: imgList,
          customButtonText: price,
          remark: spec,
          totalCount: 10,
          prop: ctx.data.prop
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          var data = res.data;
          if (data && 0 === data.ret) {
            wx.showToast({
              title: "发布成功",
              icon: 'success',
              success() {
                wx.navigateBack({
                  delta: 1
                })
              },
              duration: 1000
            });
          } else {
            wx.showToast({
              title: data.msg,
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail() {},
        complete() {
          wx.hideLoading()
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function () {

  }
}))